package com.command.demo3;

import java.util.ArrayList;
import java.util.List;

import com.command.demo3.face.Command;
import com.command.demo3.face.NoCommand;

/**
 * 调用者
 * 
 * @author Administrator
 * 
 */
public class RemoteControlWithUndo {

	Command[] onCommands;
	Command[] offCommands;
	Command undoCommand;
	List<Command> undoCommandList;

	/**
	 * 初始化7排按钮，默认不执行任何操作
	 */
	public RemoteControlWithUndo() {

		undoCommandList = new ArrayList<Command>();
		onCommands = new Command[7];
		offCommands = new Command[7];

		Command noCommand = new NoCommand();
		for (int i = 0; i < 7; i++) {
			onCommands[i] = noCommand;
			offCommands[i] = noCommand;
		}

		undoCommand = noCommand;
		undoCommandList.add(noCommand);
	}

	public void setCommand(int slot, Command onCommand, Command offCommand) {
		onCommands[slot] = onCommand;
		offCommands[slot] = offCommand;
	}

	public void onButtonWasPushed(int slot) {
		onCommands[slot].execute();
		// 记录当前的对象，用于撤销
		undoCommand = onCommands[slot];
		undoCommandList.add(undoCommand);
	}

	public void offButtonWasPushed(int slot) {
		offCommands[slot].execute();
		// 记录当前的对象，用于撤销
		undoCommand = offCommands[slot];
		undoCommandList.add(undoCommand);
	}

	public void undoButtonWasPushed() {
		int index = undoCommandList.size();
		if (index > 0) {
			index = index - 1;
			undoCommand = undoCommandList.get(index);
			undoCommandList.remove(index);
			undoCommand.undo();
		}
	}

	public String toString() {
		StringBuffer stringBuff = new StringBuffer();
		stringBuff.append("\n------ Remote Control -------\n");
		for (int i = 0; i < onCommands.length; i++) {
			stringBuff.append("[slot " + i + "] "
					+ onCommands[i].getClass().getName() + "    "
					+ offCommands[i].getClass().getName() + "\n");
		}
		stringBuff.append("[undo] " + undoCommand.getClass().getName() + "\n");
		return stringBuff.toString();
	}
}
